package cn.itcast.bos.web.action.system;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.Standard;
import cn.itcast.bos.domain.page.PageBean;
import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.domain.utils.BaseAction;
import cn.itcast.bos.service.system.UserService;

@ParentPackage("json-default")
@Namespace("/")
@Scope("prototype")
@Controller
public class UserAction extends BaseAction<User> {

	@Autowired
	private UserService userService;

	@Action(value = "user_login", results = { @Result(name = "login", type = "redirect", location = "login.html"),
			@Result(name = "success", type = "redirect", location = "index.html") })
	public String login_user() {
		// 用户和密码都保存在Model中
		// 基于Shiro登录
		Subject subject = SecurityUtils.getSubject();

		// 用户名和密码信息
		AuthenticationToken token = new UsernamePasswordToken(model.getUsername(), model.getPassword());

		try {
			subject.login(token);
			return SUCCESS;
		} catch (AuthenticationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return LOGIN;
		}

	}

	@Action(value = "user_logout", results = { @Result(name = "success", type = "redirect", location = "/login.html") })
	public String logout() {
		// 基于shiro完成退出
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return SUCCESS;
	}

	@Action(value = "user_list", results = {
			@Result(name = "success", type = "json") })
	public String login_list() {
		Pageable pageable = new PageRequest(page-1, rows);
		
		Specification<User> spec = new  Specification<User>() {
			/***
			 * root:用于获得属性字段 CriteriaQuery:可以用于简单条件查询 CriteriaBuilder:用于构造复杂条件查询
			 */
			@Override
			public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> pred = new ArrayList<Predicate>();

				// 判断条件是否为空
				if (StringUtils.isNotBlank(model.getGender())) {
					Predicate p1 = cb.equal(root.get("gender").as(String.class), model.getGender());
					pred.add(p1);
				}
				if (StringUtils.isNotBlank(model.getUsername())) {
					Predicate p2 = cb.like(root.get("userName").as(String.class), "%" + model.getUsername() + "%");
					pred.add(p2);
				}
				if (model.getBirthday()!=null) {
					Predicate p3 = cb.equal(root.get("birthday()").as(String.class), model.getBirthday());
					pred.add(p3);
				}

				return cb.and(pred.toArray(new Predicate[0]));
			}
		};
		
		
		Page<User> users= userService.findAll(spec,pageable);
		PageBean<User> use = new PageBean<User>();
		use.setPageData(users.getContent());
		use.setTotalCount(users.getTotalElements());
		ServletActionContext.getContext().getValueStack().push(use);
		return SUCCESS;
	}
	
	@Action(value="user_save",results={@Result(name="success",type="redirect",location="/pages/system/userlist.html")})
	public String user_save(){
		
		userService.save(model,roleIds);
		
		return SUCCESS;
		
	}
	
	private String[] roleIds;

	public void setRoleIds(String[] roleIds) {
		this.roleIds = roleIds;
	}

}
